package com.tsl.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.tsl.reggie.common.R;
import com.tsl.reggie.domain.dto.DishDto;
import com.tsl.reggie.domain.po.Dish;
import com.tsl.reggie.domain.po.DishFlavor;
import com.tsl.reggie.mapper.DishMapper;
import com.tsl.reggie.service.IDishFlavorService;
import com.tsl.reggie.service.IDishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author 唐书亮
 * @since 2024-01-20
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements IDishService {
    @Autowired
    private IDishFlavorService dishFlavorService;

    @Override
    public R<String> updateDishWithFlavor(DishDto dishDto) {
        //修改菜品信息
       updateById(dishDto);
        //操作flavor表,删除原来的菜品口味
        LambdaUpdateWrapper<DishFlavor> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(updateWrapper);
        //插入新的菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //给口味实体的dishId赋值
        flavors = flavors.stream().map((item) ->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);
        return R.success("修改成功");
    }

    @Override
    public R<DishDto> selectBack(Long id) {
        //通过id查询到菜品信息和菜品口味信息
        Dish dish = getById(id);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> listFlavor = dishFlavorService.list(queryWrapper);
        //创建DishDto并且将Dish里的值赋值给它,并且设置flavor的值
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        dishDto.setFlavors(listFlavor);
        return R.success(dishDto);
    }

    @Override
    public R<String> saveDishFlavor(DishDto dishDto) {
        //保存dishDto里的数据到dish表
        save(dishDto);
        //处理dishDto里的flavor数据,将dishId加入进去
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();
        //通过流的方式将dishId赋值进去
        flavors = flavors.stream().map((item) ->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        //保存dishFlavor到dish_flavor表里
        dishFlavorService.saveBatch(flavors);
        return R.success("保存成功");
    }
}
